<?
namespace app\api\controller;
use create_order_number\SnowFlake;
use think\facade\Db;

class Forms{
    public function getForms(){
        $data = request()->param();
        $token = request()->header('token');
        $checkToken = checkToken($token);
        $page = (int)$data['page'];
        $limit = (int)$data['limit'];
        unset($data['page']);
        unset($data['limit']);
        $result2['admin_id'] = ['=',$data['admin_id']??''];
        $result2['phone'] = ['like',empty($data['phone'])?'':'%'.$data['phone'].'%'];
        $result2['submit_time'] =  ['between', [$data['date1'] ?? '',$data['date2'] ?? '']];
        $w = array();
        foreach($result2 as $k=>$v) {
            if(is_array($v[1])){
                $start_time = $v[1][0];
                $end_time = $v[1][1];
                if($start_time!=""&&$end_time!=""){
                    $w[] = "$k $v[0] '$start_time' AND '$end_time'";
                }
            }else{
                if($v[1]!=""){
                    $w[] = "$k $v[0] '$v[1]'";
                }
            }

        }
        $where = join(' and ', $w);



        $admin_id = $checkToken['data']->uid;
        $my_admin = Db::table('admin')->where('admin_id',$admin_id)->find();
        switch ($my_admin['admin_roles']){
            case 1://管理员，查询全部数据
                $res = Db::table('forms')
                    ->filter(function($user){
                        $user['admin_name'] = Db::table('admin')->where('admin_id',$user['admin_id'])->value('admin_name');
                        $user['url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/#/?code='.$user['forms_code'];
                        $user['forms_content'] = json_decode($user['forms_content'],true);
                        return $user;
                    })
                    ->where($where)
                    ->page($page,$limit)
                    ->select();
                $count =  Db::table('forms')
                    ->where($where)
                    ->count();
                break;
            case 2://业务员查询，自己开账号的所有数据
                $admin_id_arr =  Db::table('admin')->where('admin_pid',$admin_id)->column('admin_id');
                array_unshift($admin_id_arr,$admin_id);
                // var_dump($admin_id_arr);
                $res = Db::table('forms')
                    ->filter(function($user){
                        $user['admin_name'] = Db::table('admin')->where('admin_id',$user['admin_id'])->value('admin_name');
                        $user['url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/#/?code='.$user['forms_code'];
                        $user['forms_content'] = json_decode($user['forms_content'],true);
                        return $user;
                    })
                    ->whereIn('admin_id',$admin_id_arr)
                    ->where($where)
                    ->page($page,$limit)
                    ->select();
                $count = Db::table('forms')
                    ->whereIn('admin_id',$admin_id_arr)
                    ->where($where)
                    ->count();
                break;
            case 3://客户，只返回自己的数据
                $res =  Db::table('forms')
                    ->filter(function($user){
                        $user['admin_name'] = Db::table('admin')->where('admin_id',$user['admin_id'])->value('admin_name');
                        $user['url'] = $_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['HTTP_HOST'].'/#/?code='.$user['forms_code'];
                        $user['forms_content'] = json_decode($user['forms_content'],true);
                        return $user;
                    })
                    ->where('admin_id',$admin_id)
                    ->where($where)
                    ->page($page,$limit)
                    ->select();

                $count = Db::table('forms')
                    ->where('admin_id',$admin_id)
                    ->where($where)
                    ->count();
                break;
        }

        return json(['status'=>200,'data'=>$res,'total'=>$count]);
    }
    private function formsGenAppNo($length=6){
        $datacenterId = rand(1, 4);//数据id
        $machineId = rand(1,31);//机器id
        $sf = new SnowFlake($datacenterId, $machineId);
        $nextId = strval($sf->nextId());
        $len = 7;
        $str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $code = str_shuffle($str);
        $rand_code = substr($code, 0, $len);
        return $rand_code.substr($nextId, $length);
    }
    private function getAdminId(){
        $token = request()->header('token');
        $checkToken = checkToken($token);
        return $checkToken['data']->uid;
    }
    public function createForms(){
        $end_num = Db::table('admin')->where('admin_id',$this->getAdminId())->value('end_num');
        if($end_num <= 0){return json(['status'=>500,'msg'=>'您的次数不足']);}
        $data = request()->param();
        $data['forms_content'] = json_encode($data['forms_content']);
        $data['forms_code'] = $this->formsGenAppNo();
        $data['admin_id'] = $this->getAdminId();
        $data['forms_create_time'] = date("Y-m-d H:i:s");
        // 启动事务
        Db::startTrans();
        try {
            Db::table('forms')->insert($data);
            Db::table('admin')->where('admin_id',$this->getAdminId())
                ->dec('end_num')
                ->update();
            // 提交事务
            Db::commit();
            return json(['status'=>200,'msg'=>'新增成功']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return json(['status'=>500,'msg'=>'新增失败']);
        }

    }
    public function updateForms(){
        $data = request()->param();
        $data['forms_content'] = json_encode($data['forms_content'],JSON_UNESCAPED_UNICODE);
//        dump($data['forms_content']);
//        die;
        $admin_id = $this->getAdminId();
        $forms_id = $data['forms_id'];
        unset($data['forms_id']);
        unset($data['forms_code']);
        unset($data['admin_name']);
        unset($data['url']);
        unset($data['url_img']);
        $res = Db::table('forms')
            ->where('admin_id',$data['admin_id'])
            ->where('forms_id',$forms_id)
            ->update($data);
        if($res){return json(['status'=>200,'msg'=>'更新成功']);}else{return json(['status'=>500,'msg'=>'更新失败']);}
    }
    public function delForms(){
        $data = request()->param();
        $forms_id = $data['forms_id'];
        $del =  Db::table('forms')->where('forms_id',$forms_id)->delete();
        if($del){return json(['status'=>200,'msg'=>'删除成功']);}else{return json(['status'=>500,'msg'=>'删除失败']);}
    }
    public function getSubmitData(){
        $data = request()->param();
        if(isset($data['searchData']) && !empty($data['searchData'])){
            $where = [
                ['forms_id','=',$data['forms_id']],
                ['admin_id','=',$this->getAdminId()],
                ['submit_content','like',"%{$data['searchData']}%"]
            ];
        }else{
            $where = [
                ['forms_id','=',$data['forms_id']],
            ];
        }

        $res1 = Db::table('submit')->where($where)
            ->page($data['page'],$data['limit'])
            ->select()
            ->toArray();
//        $fetchSql = Db::table('submit')->where($where)
//            ->fetchSql(true)
//            ->select();
//        var_dump($fetchSql);
        if(empty($res1)){
            return json([
                'status'=>200,
                'tableHeader'=>[],
                'tableData'=>[],
                'total'=>0
            ]);
        }
        $total = Db::table('submit')->where($where)->count();
        $tableData = [];
        foreach ($res1 as  $ke=>$va){
            $content = json_decode($va['submit_content'],true);
            foreach ($content as $index=>$item){
                $tableData[$ke][$item['form_title']] = $item['form_content'];
                $tableData[$ke]['操作'] = ['submit_id'=>$va['submit_id'],'forms_id'=>$va['forms_id']];
            }
        }
        unset($where[1]);
        unset($where[2]);
        //取出header头部
        $forms_content = json_decode(Db::table('forms')->where($where)->value('forms_content'),true);
        $tableHeader = [];
        foreach ($forms_content as $k=>$v){
            $no_submit = array('map','image','button','title','editor','verification','marquee','swiper');
            if(in_array($v['form_type'],$no_submit)){
                unset($v[$k]);
            }else{
                $tableHeader[] = $v['form_title'];
            }
        }
        array_push($tableHeader,'操作');
        return json([
            'status'=>200,
            'tableHeader'=>$tableHeader,
            'tableData'=>$tableData,
            'total'=>$total
        ]);
    }
    public function delSubmit(){
        $data = request()->param();
        $where = [
            ['submit_id','=',$data['submit_id']],
            ['forms_id','=',$data['forms_id']],
            ['admin_id','=',$this->getAdminId()]
        ];
        $del = Db::table('submit')->where($where)->delete();
        if($del)return json(['status'=>200,'msg'=>'删除成功']);else return json(['status'=>200,'msg'=>'删除失败']);
    }
//    public function getSubmitData(){
//        $data = request()->param();
//        $where = [
//            ['forms_id','=',$data['forms_id']],
//        ];
//        $res1 = Db::table('submit')->where($where)
//            ->page($data['page'],$data['limit'])
//            ->select()
//            ->toArray();
//        if(empty($res1)){
//            return json([
//                'status'=>200,
//                'tableHeader'=>[],
//                'tableData'=>[],
//                'total'=>0
//            ]);
//        }
//        $total = Db::table('submit')->where($where)->count();
//        $tableData = [];
//        $tableHeader = [];
//        $maxLength = 0 ;
//        foreach ($res1 as  $ke=>$va){
//            $content = json_decode($va['submit_content'],true);
//            foreach ($content as $index=>$item){
//                $tableData[$ke][$item['form_title']] = $item['form_content'];
//                $tableData[$ke]['操作'] = $va['submit_id'];
//            }
//        }
//        //取出最长的header头部
//        foreach ($tableData as $v){
//            if(count($v)>$maxLength){
//                $maxLength = count($v);
//                $tableHeader[] = $v;
//            }
//        }
//        $tableHeader = array_keys($tableHeader[0]);
//
//        return json([
//            'status'=>200,
//            'tableHeader'=>$tableHeader,
//            'tableData'=>$tableData,
//            'total'=>$total
//        ]);
//    }
}
?>